package com.ffzx.commerce.framework.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * 麦讯通简易短信发送服务，主要用于验证码发送和，简易短信发送
 * @author hyl
 * @since 2016-04-25
 */
public class MxtSmsUtil {
	
	//默认账户信息
	private static String userId = "968236";
	private static String account = "damaichang";
	private static String password = "51zhiye@*1#8";
	private static Logger logger=Logger.getLogger(MxtSmsUtil.class);
	private static String readXMLString4TagName(String xmlStr, String tagName)
			throws Exception {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder = dbf.newDocumentBuilder();

		InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes());

		Document doc = builder.parse(inputStream); //

		// 下面开始读取
		Element root = doc.getDocumentElement(); // 获取根元素

		NodeList nodes = root.getElementsByTagName(tagName);
		Element e = (Element) nodes.item(0);

		Node t = e.getFirstChild();

		return t.getNodeValue();
	}

	private static class UTF8PostMethod extends PostMethod {
		public UTF8PostMethod(String url) {
			super(url);
		}
		@Override
		public String getRequestCharSet() {
			return "UTF-8";
		}
	}
	public static String directSend(String receivers, String content, Date sendTime) {
		// String response = "";
		String url = "http://www.mxtong.net.cn/GateWay/Services.asmx/DirectSend?";
		HttpClient httpClient = new HttpClient();
		httpClient.getParams().setBooleanParameter(
				"http.protocol.expect-continue", false);
		// String responseValue;
		PostMethod getMethod = new UTF8PostMethod(url);
		String time = "";
		if (null != sendTime) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			time = df.format(sendTime);
		}
		NameValuePair[] data = { new NameValuePair("UserID", userId),
				new NameValuePair("Account", account),
				new NameValuePair("Password", password),
				new NameValuePair("Phones", receivers),
				new NameValuePair("SendType", "1"),
				new NameValuePair("SendTime", ""),
				new NameValuePair("PostFixNumber", ""),
				new NameValuePair("Content", content) };
		getMethod.setRequestBody(data);
		getMethod.addRequestHeader("Connection", "close");
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			byte[] responseBody = getMethod.getResponseBody();
			String str = new String(responseBody, "UTF-8");
			if (str.contains("GBK")) {
				str = str.replaceAll("GBK", "UTF-8");
			}
		    logger.info("the mxt message is " + str);
			
			String retCodeValue = "";
			try {
				retCodeValue = readXMLString4TagName(str, "RetCode");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//logger.info("麦讯通接口异常："+e.getMessage());
				logger.error("麦讯通接口HttpException异常：" +"the result is " + str,e);
			}
			return retCodeValue;
			// int beginPoint = str.indexOf("<RetCode>");
			// int endPoint = str.indexOf("</RetCode>");
			// String result = "RetCode=";
			// return result + str.substring(beginPoint + 9, endPoint);
			// return getMethod.getResponseBodyAsString();
		} catch (HttpException e) {
			logger.error("麦讯通接口HttpException异常：",e);
			return "1";
		} catch (IOException e) {
			logger.error("麦讯通接口IOException异常：",e);
			return "2";
		} finally {
			getMethod.releaseConnection();
		}
	}
	
	/**
	 * 发送接口
	 * @param receivers  支持群发 请以,或者;隔开
	 * @param content 若内容未加签名标示， 则将短信内容将会在后内容末尾加上自动加上【大麦场】签名
	 * @param codeType 1为群发，0为单发
	 * @param sendTime 推送时间
	 */
	public static Map<String, String> sendMsg(String receivers, String content,int codeType,
			Date sendTime) {
		String result = "";
		if(content.indexOf("【")==-1&&content.indexOf("】")==-1){
			content = content+"【大麦场】";
		}
		if (codeType == 1) {
			result = directSend(receivers.replace(",", ";"), content, sendTime);
		} else {
			String s = "";
			for (String phone : receivers.split(",")) {
				result = directSend(phone, content, sendTime);
				if ("Sucess".equals(result)) {
					s = result;
				}
			}
			if (!"".equals(s)) {
				s = "Sucess";
			}
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("STATE",result );
		map.put("MSG", "Sucess".equals(result) ? "发送成功" : "发送失败");
		
		logger.info(account+"麦讯通短信接口发送状态，"+map.get("MSG")+"_receivers"+receivers+" content_"+content+"_date_"+sendTime);
		return map;
	}
	public static void main(String[] args) throws IOException {
		MxtSmsUtil.sendMsg("18582681891", "测试短信【大麦场】",0, new Date());
	}
}
